<script setup lang="ts">
import { ref, onMounted, computed, Ref } from 'vue'
import { Spin, Empty, Button, Tabs, TabPane, Badge, Message } from '@arco-design/web-vue'
import { IconUp } from '@arco-design/web-vue/es/icon'
import MessageCard from './MessageCard.vue'
import { useMessageStore, useUserStore } from '@/store/index'
import { pageMessageUsingPost, readUsingPost, unreadCountUsingGet } from '@/api/messageController'
const TAB_KEYS = {
  UNREAD: 'unread',
  MENTION: 'mention',
  ALL: 'all'
}
const messageStore = useMessageStore()
const userStore = useUserStore()
const messages = ref<API.MessageVo[]>([])
const loading = ref(false)
const hasMore = ref(true)
const isEmpty = ref(false)
const showBackTop = ref(false)
const activeTab = ref(TAB_KEYS.ALL)

// 消息统计
const messageCount = computed(() => ({
  total: 0
}))

// 消息获取请求参数
const messageQueryRequest = ref<API.MessageQueryRequest>({
  current: 1,
  pageSize: 10,
  status: undefined,
  type: undefined,
  noticeType: undefined,
  receiverId: userStore.user.id
})

// 加载消息
const loadMessages = async (init = false) => {
  await messageStore.getUnreadCount()

  if (loading.value || (!hasMore.value && !init)) return
  let messageData: API.MessageVo[] = []
  loading.value = true

  try {
    // 如果是初始化，重置页码
    if (init) {
      messageQueryRequest.value.current = 1
    }

    const res: any = await pageMessageUsingPost(messageQueryRequest.value)
    if (res.code === 0) {
      messageData = res.data.records

      if (init) {
        messages.value = messageData
        isEmpty.value = messageData.length === 0
        messageCount.value.total = res.data.total
      } else {
        messages.value.push(...messageData)
      }

      // 判断是否还有更多数据
      hasMore.value = messageData.length === messageQueryRequest.value.pageSize

      // 只有在成功获取数据且有数据返回时才增加页码
      if (messageData.length > 0) {
        messageQueryRequest.value.current += 1
      }
    } else {
      Message.error(res.msg || '获取消息失败')
    }
  } catch (error) {
    console.error('Failed to load messages:', error)
  } finally {
    loading.value = false
  }
}

// 处理标签页切换
const handleTabChange = async (key: any) => {
  activeTab.value = key
  // 根据标签页切换，更新消息查询请求参数
  if (key === TAB_KEYS.MENTION) {
    messageQueryRequest.value.noticeType = 1
    messageQueryRequest.value.status = undefined
  }
  if (key === TAB_KEYS.UNREAD) {
    messageQueryRequest.value.noticeType = undefined
    messageQueryRequest.value.status = 1
  }
  if (key === TAB_KEYS.ALL) {
    messageQueryRequest.value.noticeType = undefined
    messageQueryRequest.value.status = undefined
  }
  messages.value = [] // 清空当前消息
  hasMore.value = true // 重置加载状态
  messageQueryRequest.value.current = 1 // 重置页码
  await loadMessages(true) // 重新加载消息
}

// 处理滚动加载
const handleScroll = async (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, clientHeight, scrollHeight } = target

  // 显示/隐藏回到顶部按钮
  showBackTop.value = scrollTop > 300

  // 触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 50) {
    await loadMessages()
  }
}

// 回到顶部
const scrollToTop = () => {
  const container = document.querySelector('.message-list')
  if (container) {
    container.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  }
}
// 处理消息确认
const handleConfirm = async (messageId: number) => {
  // 更新消息状态
  const res: any = await readUsingPost({ messageIdList: [messageId] })
  if (res.code == 0) {
    // 将该id status同步到消息列表
    const message = messages.value.find((msg) => msg.id === messageId)
    if (message) {
      message.status = 0
    }
  } else {
    Message.error('确认失败')
  }
  await messageStore.getUnreadCount()
}

// 初始加载
onMounted(async () => {
  await loadMessages(true)
})

// 暴露方法给父组件
defineExpose({
  loadMessages
})
</script>

<template>
  <div class="message-container">
    <!-- 消息统计和分类 -->
    <div class="message-header">
      <div class="message-count">
        共 {{ messageCount.total }} 条消息
        <Badge :count="messageStore.unreadCount" :dot="false" class="unread-badge" />
      </div>
      <Tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <TabPane :key="TAB_KEYS.UNREAD" :title="`未读消息 (${messageStore.unreadCount})`" />
        <TabPane :key="TAB_KEYS.MENTION" title="@我" />
        <TabPane :key="TAB_KEYS.ALL" title="全部消息" />
      </Tabs>
    </div>

    <div class="message-list" @scroll="handleScroll">
      <!-- 空状态 -->
      <template v-if="isEmpty">
        <div class="empty-state">
          <Empty description="暂无消息" />
        </div>
      </template>

      <!-- 消息列表 -->
      <template v-else>
        <MessageCard
          v-for="msg in messages"
          :key="msg.id"
          :message="msg"
          @confirm="handleConfirm"
          class="message-item"
        />

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <Spin dot />
        </div>

        <!-- 加载完成提示 -->
        <div v-if="!hasMore && !loading" class="no-more">没有更多消息了</div>
      </template>
    </div>

    <!-- 回到顶部按钮 -->
    <div v-show="showBackTop" class="back-to-top" @click="scrollToTop">
      <Button circle>
        <IconUp />
      </Button>
    </div>
  </div>
</template>

<style scoped>
.message-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
  z-index: inherit;
}

.message-header {
  padding: 16px 20px;
  border-bottom: 1px solid var(--color-border);
  background-color: var(--color-bg-2);
  position: sticky;
  top: 0;
  z-index: 1;
  flex-shrink: 0;
  width: 100%;
  box-sizing: border-box;
}

.message-count {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--color-text-2);
  font-size: 14px;
  margin-bottom: 16px;
}

.unread-badge {
  margin-left: 8px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 20px;
  box-sizing: border-box;
  width: 100%;
}

.message-item {
  margin: 12px 0;
  padding: 12px 16px;
  background: var(--color-bg-2);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  word-break: break-all;
  overflow-wrap: break-word;
}

.message-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.loading-state {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.no-more {
  text-align: center;
  color: var(--color-text-3);
  font-size: 13px;
  padding: 16px 0;
}

.back-to-top {
  position: fixed;
  bottom: 40px;
  right: 40px;
  z-index: 10;
  transition: all 0.3s ease;
}

.back-to-top:hover {
  transform: translateY(-4px);
}

/* 响应式布局 */
@media screen and (max-width: 840px) {
  .message-list {
    padding: 0 12px;
  }

  .message-header {
    padding: 16px 12px;
  }
}

/* 优化滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-thumb {
  background-color: var(--color-text-4);
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-track {
  background-color: var(--color-fill-2);
}

/* 确保所有元素都使用 border-box */
*,
*::before,
*::after {
  box-sizing: border-box;
}

/* 确保消息卡片内的所有内容都能正确换行和限制宽度 */
:deep(.message-item) {
  .message-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 4px;
  }

  .message-content {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--color-text-2);
    font-size: 13px;
  }

  .message-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    color: var(--color-text-3);
    font-size: 12px;
  }

  .message-title {
    font-size: 14px;
    color: var(--color-text-1);
    margin: 0;
  }

  .message-time {
    color: var(--color-text-3);
    font-size: 12px;
  }

  .message-sender {
    color: var(--color-text-2);
    font-weight: 500;
  }

  .message-action {
    color: var(--color-text-3);
  }
}
</style>
